package com.by.filter;


import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import sun.security.pkcs.PKCS7;


@Component
public class TokenFilter implements GlobalFilter, Ordered {

    String secret = "admin";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 提取Token
        ServerHttpRequest request = exchange.getRequest();
        String authHeader = request.getHeaders().getFirst("Authorization");
        if (authHeader == null || !authHeader.startsWith("Base ")) {
            return handleUnauthorized(exchange, "Token不存在或格式错误");
        }
        String token = authHeader.substring(5); // 去除"Bearer "前缀


        //验证token
      boolean result =  JWTUtil.verify(token, secret.getBytes());
        if (!result) {
            return handleUnauthorized(exchange, "Token无效");
        }

        //解析token
        JWT jwt = JWTUtil.parseToken(token);
        //获取用户id
        Object userId = jwt.getPayload("id");
        //....获取其它参数

        //将参数 设置到请求头  传递给后缀的微服务
        ServerHttpRequest newRequest = request.mutate()
                .header("X-User-Id", userId.toString())
                .build();

        // 5. 转发请求到微服务
        return chain.filter(exchange.mutate().request(newRequest).build());

    }

    // 处理未授权响应（返回401）
    private Mono<Void> handleUnauthorized(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String body = "{\"code\":401,\"message\":\"" + message + "\"}";
        return response.writeWith(Mono.just(response.bufferFactory().wrap(body.getBytes())));
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
